package com.xmotor.test_consistency_component.listener;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description 最终一致性组件监听器
 * @Author Dang Xianyue
 * @Date 2020-09-24 17:41
 * @Version 1.0
 */
@Slf4j
@Component
public class ConsistencyComponentListener {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @RabbitListener(queues = "dxy_test_queue",containerFactory="rabbitListenerContainerFactory")
    public void onMessage(String result)throws Exception{
        log.info("result：" + result);
        String orderId = JSONObject.parseObject(result).getString("orderId");
        String taskId = JSONObject.parseObject(result).getString("task_id");

        if ("fail_test123".equals(orderId)){
            log.info("测试处理失败");
            feedBack(-200, "测试处理【" + orderId + "】失败", taskId);
        }else {
            log.info("测试处理成功");
            feedBack(200, "测试处理【" + orderId + "】成功", taskId);
        }


    }

    // 正常消费掉后通知mq服务器移除此条mq
    private void basicACK(Message message, Channel channel) {
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            log.error("通知服务器移除mq时异常，异常信息：" + e);
        }
    }

    // 处理异常，mq重回队列
    private void basicNACK(Message message, Channel channel) {
        try {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        } catch (IOException e) {
            log.error("mq重新进入服务器时出现异常，异常信息：" + e);
        }
    }

    //处理信息反馈
    private void feedBack(Object code, Object msg, String task_id) {
        JSONObject mqResult = new JSONObject();
        mqResult.put("code", code);
        mqResult.put("msg", msg);
        mqResult.put("task_id", task_id);
        mqResult.put("target_queue", "dxy_test_queue");
        amqpTemplate.convertAndSend("consistency.messageFeedback", mqResult);
    }
}
